import { ref, reactive, onMounted } from '@vue/composition-api'
//   加载地图js文件
function loadMapScript(ak) {
    if (!global.BMap) {
      // 没有加载过BMap？
      global.BMap = {}
      global.BMap._preloader = new Promise(resolve => {
        // 创建地图script
        const $script = document.createElement('script')
        global.document.body.appendChild($script)
        $script.src = `https://api.map.baidu.com/api?v=3.0&ak=${ak}&callback=_initBaiduMap`
  
        // 百度地图js文件加载完成回调函数
        global._initBaiduMap = function() {
          resolve(global.BMap) // 成功回调
          global.document.body.removeChild($script)
          global.BMap._preloader = null
          global._initBaiduMap = null
        }
      })
  
      return global.BMap._preloader
    } else if (!global.BMap._preloader) {
      // 通过其他方式加载过 ？
      return Promise.resolve(global.BMap)
    } else {
      // 已经通过 本方法加载过
      return global.BMap._preloader
    }
  }
  export default function initMap(callback){
    const mapEl = ref(null)
    // const map = ref(null)
    // const BMap = ref(null)
    // map 做成非响应式 节省vue性能
    const Bm = {
        map: null,
        BMap: null
    } 
    // 如ak无效去https://lbs.baidu.com/apiconsole/key#/home申请
    const ak = '6UrAjgav2UvGflDGvmL4ukt2z2nlCYLi'

    const loadMap = () => {

    // 将此标签放到index.html中 不使用异步加载百度地图包（loadMapScript）防止 数据请求请求到后地图还没加载导致错误
    // <script src="https://api.map.baidu.com/api?v=3.0&ak=6UrAjgav2UvGflDGvmL4ukt2z2nlCYLi"></script>
    // loadMapScript(ak).then(initMap)
    initMap(global.BMap || global.BMapGL)
    }
    const initMap = (BMp) => {
      var mp = new BMp.Map(mapEl.value) // 创建Map实例
      var point = new BMp.Point(104.807684, 30.0085205) // 创建点坐标
      mp.centerAndZoom(point, 10)
      mp.enableScrollWheelZoom()

      Bm.map = mp
      Bm.BMap = BMp

      callback && callback(mp,BMp)
    }

    // function drivingRoute() {
    //   const map = Bm.map
    //   const BMap = Bm.BMap
    //   var p1 = new BMap.Point(104.188365, 30.627248)
    //   var p2 = new BMap.Point(105.427002, 29.389793)
    //   var driving = new BMap.DrivingRoute(map, { renderOptions: { map: map, autoViewport: true }})
    //   driving.search(p1, p2)
    // }

    // onMounted(() => {
    //   drivingRoute()
    // })

    onMounted(loadMap)

    return {
        mapEl,
        // map,
        // BMap,
        Bm
    }
  }